//1. 导入 createSlice 函数
import {createSlice, createAsyncThunk} from '@reduxjs/toolkit'
//导入 axios
import axios from 'axios';

//新的异步 action creator
export let asyncAddTodo = createAsyncThunk('todo/asyncAdd', async (title, thunk) => {
  //发送请求 新增任务
  let result = await axios.post('http://localhost:3001/todo', {title: title, done: false});
  //返回结果值
  thunk.dispatch(add(result.data));
});

//2. 创建 slice 切片对象
let slice = createSlice({
  //状态的名称
  name: 'todo',
  //状态的初始值
  initialState: [], 
  //定义 reducer 内部的功能
  reducers: {
    init: (state, {type, payload}) => {
      //将获得的任务压入到 state 数组中
      state.push(...payload);
    },
    add: (state, {type, payload}) => {
      state.push(payload);
    }
  },
  //
  extraReducers: (builder) => {
    //当 asyncAddTodo 异步任务成功的时候, 执行该回调, 更新 redux 中的状态
    // builder.addCase(asyncAddTodo.fulfilled, (state, {type, payload}) => {
    //   state.push(payload);
    // })
  }
});

//获取 action creator
let {init, add} = slice.actions;

//声明异步的 action creator
export let asyncGetAllTodos = () => {
  //返回一个函数
  return async dispatch => {
    //发送请求 获取所有的 todo
    let result = await axios.get('http://localhost:3001/todo'); 
    //同步更新 redux 中的状态
    dispatch(init(result.data));
  }
}


//获得 reducer 函数
let reducer = slice.reducer;

//暴露 reducer 函数
export default reducer;